from flask import Blueprint, request, render_template, session, jsonify, g, redirect, url_for

user_blueprint = Blueprint('user', __name__, url_prefix='/user')


@user_blueprint.route('/login', methods=['GET', 'POST'])
def user_login():
    if request.method == 'GET':
        return render_template('user/login.html')
    elif request.method == 'POST':
        user_name = request.form.get('user_name', '')
        user_pwd = request.form.get('user_pwd', '')
        if user_name and user_pwd and user_name == 'admin' and user_pwd == 'crane-machine':
            session['user'] = {"user_name": user_name}
            g.msg['status'] = 'ok'
        else:
            g.msg['message'] = "用户名密码为空或不正确"
        return jsonify(g.msg)


@user_blueprint.route('/logout', methods=['GET'])
def user_logout():
    session.clear()
    return redirect(url_for('.user_login', _external=True))
